package com.cn.wanxi.servlet.product;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.model.ProductModel;
import com.cn.wanxi.service.ProductService;
import com.cn.wanxi.service.impl.ProductServiceImpl;
import com.cn.wanxi.util.Upload;
import com.cn.wanxi.util.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/backFile/product/add")
public class ProductAddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JSONObject jsonObject = new JSONObject();
        if (req.getSession().getAttribute("username") == null) {
            jsonObject.put("result", "notLogin");
        } else {
            Upload.file(req);
//        取值
            String name = (String) req.getAttribute("name");
            String price = (String) req.getAttribute("price");
            String cuisine = (String) req.getAttribute("cuisine");
            String imgHref = (String) req.getAttribute("imgHref");
            String content = (String) req.getAttribute("content");
//        封装model
            ProductModel productModel = new ProductModel();
            productModel.setName(name);
            productModel.setPrice(Tool.stringToFloat(price));
            productModel.setCuisineId(Tool.stringToInt(cuisine));
            productModel.setImgHref(imgHref);
            productModel.setContent(content);
//        调用服务逻辑层
            ProductService productService = new ProductServiceImpl();
//        返回数据
            String result = productService.add(productModel);
//        返回页面
            jsonObject.put("result", result);
        }
        resp.getWriter().println(jsonObject);
    }
}
